<?php

require_once('jhtraq.php');
class JhtraqModelReleases extends JhtraqModelJhtraq
{
	
	function get($id = 0)
	{
		$this->db->setQuery("Select * from #__jhtraq_releases where id='$id'");
		return $this->db->loadObject();
	}
	
	function getPaged()
	{
		$mainframe =& JFactory::getApplication();
		$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		jimport('joomla.html.pagination');
		$search = JRequest::getVar('search');
		$project = (int)JRequest::getVar('project');
		
		$query = "Select SQL_CALC_FOUND_ROWS * from #__jhtraq_releases";
		if($search != '')
		$query .= "Where name like'%$search%' ";
		if($project > 0 && $search != '')
		{
			$query .= " AND project_id='$project'";
		}elseif($project > 0 && $search == '')
		{
			$query .= " Where project_id='$project'";
		}
		
		$query .= ' ORDER BY id desc';
		
		$this->db->setQuery($query,$limitstart, $limit );
		$r =&$this->db->loadAssocList();
		//	print_r($this->db);
		
		$this->db->setQuery('SELECT FOUND_ROWS();');
		$this->_pagination = new JPagination( $this->db->loadResult(), $limitstart, $limit );
		
		return $r;
	}
	
	function save($post)
	{

		$id = (int)$post['id'];
		$name = $this->db->getEscaped($post['name']);
		$project_id = (int)$post['project_id'];
		$version_id = (int)$post['version_id'];
		$jhshop_prod_id = (int)$post['jhshop_prod_id'];
                $ambrasubs_types = implode(",",$post['ambrasubs_types']);
		$download_link = $this->db->getEscaped($post['download_link']);
		$download_size = $this->db->getEscaped($post['download_size']);
		$released = strtotime($post['released']);
		$published = (int)$post['published'];
		
		$q = "Set name='$name',project_id='$project_id',version_id='$version_id',jhshop_prod_id='$jhshop_prod_id',ambrasubs_types='$ambrasubs_types',download_link='$download_link',released='$released',published='$published',download_size='$download_size'";
		if($id > 0)
		{
			//update
			$query = "Update #__jhtraq_releases " . $q . " where id='$id'";
		}else{
			//insert
			$query = "Insert into #__jhtraq_releases " . $q;
		}
		$this->db->setQuery($query);
		return $this->db->query();
	}
	
	/**
	 * Remove a release
	 * 
	 * @param array $ids An array of ids of the release to remove
	 */
	public function remove($ids) {
		foreach($ids as $id) {
			$id = $this->db->getEscaped($id);
			$query = "DELETE from #__jhtraq_releases where id='$id'";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}
}